package com.linxz.video.videoplayer.view;

import android.content.Context;
import android.graphics.SurfaceTexture;
import android.graphics.drawable.AnimationDrawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import androidx.annotation.NonNull;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.Surface;
import android.view.TextureView;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.linxz.video.R;
import com.linxz.video.videoplayer.event.VideoPlayerListener;

/**
 * @author Linxz
 * 创建日期：2019年10月15日 15:04
 * version：v4.5.4
 * 描述：
 */
public class CustomVideoView extends RelativeLayout {

    private RelativeLayout mPlayerView;
    private TextureView textureView;
    private ImageView imgToFullView;
    private ImageView imgLoading;
    private Button btnPlayer;
    private VideoPlayerListener mVideoPlayerListener;

    private Surface videoSurface;

    private boolean canPlay = true;
    private PlayStatus playStatus=PlayStatus.IDLE;
    private boolean mIsRealPause;
    private boolean mIsComplete;

    private String sourcePath;
    private boolean isMute;
    private int mScreenWidth, mDestationHeight;

    private MediaPlayer mediaPlayer;



    enum PlayStatus {
        IDLE,
        PREPARE,
        PLAYING,
        START,
        PAUSE,
        STOP,
        COMPLETE,
        ERROR,
        END,
        DESTROY
    }


    public CustomVideoView(Context context) {
        super(context);
        init();
        setListener();
    }

    private void init() {
        mPlayerView = (RelativeLayout) LayoutInflater.from(getContext()).inflate(R.layout.lib_video_player_layout, this);
        textureView = mPlayerView.findViewById(R.id.textureView);
        checkMediaPlayer();
        initSmallLayoutMode();
    }

    private void setListener() {
        textureView.setSurfaceTextureListener(mSurfaceTextureListener);
        textureView.setOnClickListener(mVideoClick);
        imgToFullView.setOnClickListener(mFullScreenClick);
        btnPlayer.setOnClickListener(mPlayClick);
    }

    /**
     * 小屏模式，屏幕占比16：9
     * */
    private void initSmallLayoutMode(){
        DisplayMetrics dm = new DisplayMetrics();
        WindowManager wm = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
        if (wm!=null){
            wm.getDefaultDisplay().getMetrics(dm);
            mScreenWidth = dm.widthPixels;
            mDestationHeight = (int) (mScreenWidth * (9 / 16.0f));
        }
        LayoutParams params = new LayoutParams(mScreenWidth, mDestationHeight);
        params.addRule(RelativeLayout.CENTER_IN_PARENT);
        mPlayerView.setLayoutParams(params);
        imgToFullView = mPlayerView.findViewById(R.id.imgToFullView);
        imgLoading = mPlayerView.findViewById(R.id.imgLoading);
        btnPlayer = mPlayerView.findViewById(R.id.btnPlayer);
    }

    public void setVideoPlayerListener(VideoPlayerListener listener){
        this.mVideoPlayerListener=listener;
    }

    public void setDataSource(String sourcePath) {
        this.sourcePath = sourcePath;
    }

    private void checkMediaPlayer(){
        if (mediaPlayer!=null){
            return;
        }
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setOnPreparedListener(mOnPreparedListener);
        mediaPlayer.setOnCompletionListener(mOnCompletionListener);
        mediaPlayer.setOnErrorListener(mOnErrorListener);
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    }

    public void load() {
       try {
           if (playStatus != PlayStatus.IDLE) {
               return;
           }
           showLoading();
           mute(true);
           mediaPlayer.setDataSource(sourcePath);
           mediaPlayer.prepareAsync();
       }catch (Exception e){
           e.printStackTrace();
       }
    }


    private void showLoading() {
        imgToFullView.setVisibility(View.GONE);
        btnPlayer.setVisibility(View.GONE);
        imgLoading.setVisibility(View.VISIBLE);
        AnimationDrawable anim = (AnimationDrawable) imgLoading.getBackground();
        anim.start();
    }

    private void showPlayView(){
        imgLoading.clearAnimation();
        imgLoading.setVisibility(View.GONE);
    }

    private void showPauseView(boolean show){
        imgToFullView.setVisibility(show? View.VISIBLE : View.GONE);
        btnPlayer.setVisibility(show? View.GONE : View.VISIBLE);
        imgLoading.clearAnimation();
        imgLoading.setVisibility(View.GONE);
    }

    public void resume(){
        if (playStatus!=PlayStatus.PREPARE && playStatus!=PlayStatus.COMPLETE && playStatus!=PlayStatus.PAUSE){
            return;
        }
        if (!isPlaying()){
            playStatus=PlayStatus.PLAYING;
            mediaPlayer.setOnSeekCompleteListener(null);
            mediaPlayer.start();
            showPauseView(true);
        }else{
            showPauseView(false);
        }
    }

    public void pause(){
        if (playStatus!=PlayStatus.PLAYING){
            return;
        }
        playStatus=PlayStatus.PAUSE;
        if (isPlaying()){
            mediaPlayer.pause();
        }else{
            showPauseView(false);
        }
    }

    public void stop(){
        if (mediaPlayer!=null){
            mediaPlayer.reset();
            mediaPlayer.setOnSeekCompleteListener(null);
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer=null;
        }
        playStatus=PlayStatus.IDLE;
        showPauseView(false);
    }

    public void onDestroy(){
        if (mediaPlayer!=null){
            mediaPlayer.reset();
            mediaPlayer.setOnSeekCompleteListener(null);
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer=null;
        }
        playStatus=PlayStatus.IDLE;
        showPauseView(false);
    }

    /**
     * 设置是否静音
     * */
    public void mute(boolean mute){
        this.isMute=mute;
        if (mediaPlayer!=null){
            float volume=isMute? 0.0f : 1.0f;
            mediaPlayer.setVolume(volume,volume);
        }
    }

    public boolean isPlaying(){
        return mediaPlayer != null && mediaPlayer.isPlaying();
    }

    public int getCurrentPosition() {
        if (this.mediaPlayer != null) {
            return mediaPlayer.getCurrentPosition();
        }
        return 0;
    }

    public void isShowFullBtn(boolean isShow) {
        imgToFullView.setImageResource(isShow ? R.drawable.xadsdk_ad_mini : R.drawable.xadsdk_ad_mini_null);
        imgToFullView.setVisibility(isShow ? View.VISIBLE : View.GONE);
    }

    /**
     * 全屏不显示暂停状态,后续可以整合，不必单独出一个方法
     * */
    public void pauseForFullScreen() {
        if (playStatus != PlayStatus.PLAYING) {
            return;
        }
        playStatus=PlayStatus.PAUSE;
        if (isPlaying()) {
            mediaPlayer.pause();
            if (!this.canPlay) {
                mediaPlayer.seekTo(0);
            }
        }
    }

    /**
     * 跳到指定点播放视频
     * */
    public void seekAndResume(int position) {
        if (mediaPlayer != null) {
            showPauseView(true);
            entryResumeState();
            mediaPlayer.seekTo(position);
            mediaPlayer.setOnSeekCompleteListener(new MediaPlayer.OnSeekCompleteListener() {
                @Override
                public void onSeekComplete(MediaPlayer mp) {
                    mediaPlayer.start();
                }
            });
        }
    }

    /**
     * 进入播放状态时的状态更新
     */
    private void entryResumeState() {
        canPlay = true;
        playStatus=PlayStatus.PLAYING;
        setIsRealPause(false);
        setIsComplete(false);
    }

    /**
     * 播放完成后回到初始状态
     * */
    public void playBack() {
        playStatus=PlayStatus.PAUSE;
        if (mediaPlayer != null) {
            mediaPlayer.setOnSeekCompleteListener(null);
            mediaPlayer.seekTo(0);
            mediaPlayer.pause();
        }
        this.showPauseView(false);
    }

    public boolean isRealPause() {
        return mIsRealPause;
    }

    public boolean isComplete() {
        return mIsComplete;
    }

    public void setIsComplete(boolean isComplete) {
        mIsComplete = isComplete;
    }

    public void setIsRealPause(boolean isRealPause) {
        this.mIsRealPause = isRealPause;
    }

    @Override
    protected void onVisibilityChanged(@NonNull View changedView, int visibility) {
        super.onVisibilityChanged(changedView, visibility);
        if (visibility==VISIBLE && playStatus==PlayStatus.PAUSE){

        }else{

        }
    }

    private TextureView.SurfaceTextureListener mSurfaceTextureListener = new TextureView.SurfaceTextureListener() {
        @Override
        public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
            //自动加载
            videoSurface = new Surface(surface);
            mediaPlayer.setSurface(videoSurface);
            load();
        }

        @Override
        public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {

        }

        @Override
        public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
            return false;
        }

        @Override
        public void onSurfaceTextureUpdated(SurfaceTexture surface) {

        }
    };

    private MediaPlayer.OnPreparedListener mOnPreparedListener = new MediaPlayer.OnPreparedListener() {
        @Override
        public void onPrepared(MediaPlayer mp) {
            //加载成功
            playStatus = PlayStatus.PREPARE;
            if (mVideoPlayerListener != null) {
                mVideoPlayerListener.onVideoLoadSuccess();
            }
            showPlayView();
            resume();
        }
    };

    private MediaPlayer.OnErrorListener mOnErrorListener = new MediaPlayer.OnErrorListener() {
        @Override
        public boolean onError(MediaPlayer mp, int what, int extra) {
            playStatus = PlayStatus.ERROR;
            if (mVideoPlayerListener != null) {
                mVideoPlayerListener.onVideoLoadError();
            }
            return false;
        }
    };

    private MediaPlayer.OnCompletionListener mOnCompletionListener = new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mp) {
            playStatus = PlayStatus.COMPLETE;
            playBack();
            setIsComplete(true);
            setIsRealPause(true);
        }
    };


    private OnClickListener mPlayClick=new OnClickListener() {
        @Override
        public void onClick(View v) {
            if (playStatus==PlayStatus.PAUSE){
                resume();
                if (mVideoPlayerListener!=null){
                    mVideoPlayerListener.onPlayClick();
                }
            }else{
                load();
            }
        }
    };


    private OnClickListener mFullScreenClick=new OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mVideoPlayerListener != null) {
                mVideoPlayerListener.onFullScreenClick();
            }
        }
    };


    private OnClickListener mVideoClick=new OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mVideoPlayerListener != null) {
                mVideoPlayerListener.onVideoClick();
            }
        }
    };


}
